from flask import Flask
app = Flask(__name__)
import datetime, sqlite3, os, sys
from flask import render_template, url_for, request, redirect, send_from_directory

#http://blog.csdn.net/junshao90/article/details/8706342
BASE_DIR = sys.path[0]
if os.path.isfile(BASE_DIR):
	BASE_DIR = os.path.dirname(BASE_DIR)

try :
	os.mkdir(os.path.join(BASE_DIR, 'media'))
except FileExistsError :
	pass

def file_insert(name_raw, name_new, category, size, download=0) :
	'返回加入 file 的操作语句'
	t = "insert into file(name_raw, name_new, category, size, download) "
	t += "values('%s', '%s', '%s', '%s', '%s')"
	return t % (name_raw, name_new, category, size, download)

cx = sqlite3.connect("mydoc.db")
cu = cx.cursor()
try :
	cu.execute('''create table file (
		id integer primary key, 
		name_raw varchar(100), 
		name_new varchar(100), 
		category varchar(100), 
		size integer, 
		download integer
	)''')
except sqlite3.OperationalError :
	pass
cx.commit()

def fname_create(fname) :
	suffix = fname.split('.')[-1]
	tid = str(datetime.datetime.now())
	return '[%s].%s' % (tid, suffix)

def byte_exchange(byte_size) :
	if byte_size < 1024**1 :
		mod = (1024**0, 'B')
	elif byte_size < 1024**2 :
		mod = (1024**1, 'KiB')
	elif byte_size < 1024**3 :
		mod = (1024**2, 'MiB')
	elif byte_size < 1024**4 :
		mod = (1024**3, 'GiB')
	else :
		mod = (1024**4, 'TiB')
	return '%.1f %s' % (byte_size / mod[0], mod[1])

@app.route('/')
def main_page():
	cu = sqlite3.connect("mydoc.db").cursor()
	category_qry = set()
	for i in cu.execute("select * from file").fetchall() :
		category_qry.add(i[3])
	category_list = []
	for i in list(category_qry) :
		category_list += [{
			'name': i, 'href': '/category/%s/' % i
		}]
	return render_template('home.html', cl=category_list)

@app.route('/category/<cname>/')
def category_page(cname):
	cu = sqlite3.connect("mydoc.db").cursor()
	category_qry = cu.execute \
		("select * from file where category='%s'" % cname).fetchall()
	file_list = []
	for i in category_qry :
		file_list += [{
			'id': i[0], 
			'name': i[1], 
			'href': '/download/%s/' % i[2], 
			'size': byte_exchange(i[4]), 
			'download': i[5], 
		}]
	return render_template('list.html', fl=file_list, cname=cname)

@app.route('/upload/', methods=['POST','GET'])
def upload():
	if request.method == 'POST' :
		f = request.files.get('upload_file')
		category = request.form.get('category', '')
		password = request.form.get('password', '')
		if password not in ('qiangjiqing', 'shiyiquan') :
			return render_template('upload.html', error="密码不正确")
		if not f:
			return render_template('upload.html', error="没有选择文件")
		if not category:
			return render_template('upload.html', error="没有写明类型")
		fname = f.filename
		name_new = fname_create(fname)
		path = os.path.join(BASE_DIR, 'media', name_new)
		f.save(path)
		size = os.path.getsize(path)
		cx = sqlite3.connect("mydoc.db")
		cu = cx.cursor()
		cu.execute(file_insert(fname, name_new, category, size))
		cx.commit()
		return redirect('/category/%s/' % category)
	else :
		return render_template('upload.html')

@app.route('/download/<path:filename>')
def download_file(filename) :
	cx = sqlite3.connect("mydoc.db")
	cu = cx.cursor()
	name_new = filename.split('/')[0]
	qry_exe = cu.execute("select * from file where name_new='%s'" % name_new)
	qry = qry_exe.fetchall()[0]
	cu.execute("update file set download=%d where id=%d" % (qry[5] + 1, qry[0]))
	cx.commit()
	return send_from_directory(BASE_DIR + '/media', filename, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True)

